import {langs} from './uiLangs';
import notification from 'antd/lib/notification'
import $ from 'jquery';
import axios from 'axios';
import qs from 'qs';
import store  from 'store';
import _globConfig from './config';
import {getUIList} from './uiConfig';

export const currentUser = {};

const __charArray = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

/**
 * 实际运行时AJAX
 */
const ajaxInstance = axios.create({
	baseURL: _globConfig.apiBaseURL,
	timeout: 0,
});

/**
 * 本地调试用AJAX
 */
const testAjaxInstance = axios.create({
	baseURL: _globConfig.testBaseURL,
	timeout: 100000,
});

ajaxInstance.defaults.withCredentials = true;
ajaxInstance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

ajaxInstance.defaults.transformRequest = [(data,options) => {

	if('multipart/form-data' === options['Content-Type']){
		return data;
	}
	
	if(isNull(data) === false && isNull(currentUser.userId) === false){
		if('application/json' !== options['Content-Type']){
			data = data + '&_userId=' + currentUser.userId;
		}
	}
	else if(isNull(currentUser.userId) === false){
		if('application/json' !== options['Content-Type']){
			data = '_userId=' + currentUser.userId;
		}
	}
	//console.log(data);
	return data;
}];
/**
 * AJAX请求
 */
export function ajaxFormData(url, params, callBack) {
	//console.log(params);
	return new Promise((resolve, reject) => {

		ajaxInstance.post(url, params, { headers: {'Content-Type': 'multipart/form-data'} })
			.then(function (response) {
				if (callBack !== undefined || typeof (callBack) === 'function') {
					callBack(response.data);
				}
				resolve(response.data);
			})
			.catch(function (error) {
				if (callBack !== undefined) {
					callBack(error);
				}
				reject(error);
			});

	});
}

/**
 * AJAX请求
 */
export function ajax(url, params, callBack,contentType) {
	
	return new Promise((resolve, reject) => {
		const config = {};
		let postData = '';
		if(contentType !== undefined){
			config.headers = {'Content-Type': contentType};
			if('application/json' === contentType){
				postData = JSON.stringify(params);
			}
			else if('multipart/form-data' === contentType){
				postData = params;
			}
		}
		else{
			postData = qs.stringify(params, { arrayFormat: 'repeat'});
		}

		//console.log(postData);

		if(url !== undefined && url.indexOf('.json') !== -1){
			testAjaxInstance.get(url, postData,config)
			.then(function (response) {
				if (isNull(callBack ) === false || typeof (callBack) === 'function') {
					callBack(response.data);
				}
				resolve(response.data);
			})
			.catch(function (error) {
				if (isNull(callBack ) === false || typeof (callBack) === 'function') {
					callBack(error);
				}
				reject(error);
			});
		}
		else{
			ajaxInstance.post(url, postData,config)
			.then(function (response) {
				if (isNull(callBack ) === false || typeof (callBack) === 'function') {
					callBack(response.data);
				}
				resolve(response.data);
			})
			.catch(function (error) {
				if (isNull(callBack ) === false || typeof (callBack) === 'function') {
					callBack(error);
				}
				reject(error);
			});
		}

	});
}

/**
 * 批量AJAX请求
 */
export function batchAjax(urlList, paramsList, callBack) {

	let requests = urlList.map( (url,index) => {
		return ajaxInstance.post(url, qs.stringify(paramsList[index], { indices: false }))
	} );

	axios.all(requests)
    .then( (results) => {
		let datas = results.map(result => {
			return result.data;
		});
		if(callBack !== undefined){
			callBack(datas);
		}
	});
}


export function setStoreItem(key,value){
	store.set(key,value);
}

export function getStoreItem(key,defaultValue){
	let value = store.get(key);
	if(isNull(value) && isNull(defaultValue) == false){
		return defaultValue;
	}
	else{
		return value;
	}
}

export function removesetStoreItem(key){
	store.remove(key);
}

export function inArray(value,array) {
	return $.inArray(value, array);
}

export function startWith(text,str){
	var reg=new RegExp("^"+str);
	return reg.test(text);
}

export function endWith(text,str){
	var reg=new RegExp(str+"$");
	return reg.test(text);
}

/**
 * 
 * @param {地址} url 
 * @param {参数} params 
 */
export function fetchData(url,params){
	
	let fetchUrl =  startWith(url,"http") ? url : _globConfig.apiBaseURL + url;

	var response = $.ajax({url:fetchUrl,async:false,data : params});
	return response.responseJSON;
}

export function showResultMessage(operationResult) {
	if (isNull(operationResult) !== true) {
		if (operationResult.success === true) {
			openSuccessNotification(getLocalMessage(operationResult.message, operationResult.message));
		} else if (operationResult.success === false) {
			openErrorNotification(getLocalMessage(operationResult.message, operationResult.message));
		}
	}
}

export function doActionHandler(actionEvent, actionHandler, instance) {

	if (actionHandler === null || typeof actionHandler[actionEvent.action] !== 'function') {
		openErrorNotification(getLocalMessage('message.noActionFount') + '[' + actionEvent.action + ']!');
	} else {
		let operationResult = null;
		if (instance !== null) {
			operationResult = actionHandler[actionEvent.action].bind(instance)(actionEvent);
		} else {
			operationResult = actionHandler[actionEvent.action](actionEvent);
		}

		showResultMessage(operationResult);

	}
}

export function getLocalMessage(key, defaultValue) {

	//var value = $.ajax({url:_serverRoot + "/common/getLocalMessage",async:false,data : {key :objKey}});

	//return value.responseJSON;

	var lang = navigator.language.split('-')[0];

	if (isNull(langs[lang][key]) === false) {
		return langs[lang][key];
	} else {
		return defaultValue;
	}

}

/**
 * 产生随机字符
 */
export function randomString(n) {
	var res = "";
	for (var i = 0; i < n; i++) {
		var id = Math.ceil(Math.random() * 35);
		res += __charArray[id];
	}
	return res;
}

/*
 * 校验字符串是否为空
 */
export function isEmpty(str) {
	if (!str || null === str || undefined === str || "undefined" === str ||
		(!str.match && str.match("^(\s|　| )*$"))) {
		return true;
	}
	return false;
}

export function isNull(obj) {
	return obj === undefined || obj === null;
}

export function isNotNull(obj) {
	return !isNull(obj);
}

export function isPlainObject(obj) {
	return typeof (obj) !== "object"
}

export function isArrayObject( obj ){  
	//return typeof (obj) === "array";
	if (typeof Array.isArray === "function") {
		return Array.isArray(obj);
	}else{
		return Object.prototype.toString.call(obj) === "[object Array]";
	}
}

export function uniqueArray(arr){
	const hash=[];
	for (let i = 0; i < arr.length; i++) {
	   if(hash.indexOf(arr[i]) === -1){
		hash.push(arr[i]);
	   }
	}
	return hash;
}

export function getListDataMap(listId,params){
	const listDataConfig = getUIList(listId);
	const map = {};
	if(listDataConfig.type !== 'static'){
		return loadListData(listDataConfig.type,listDataConfig.dataProperty,listDataConfig.labelProperty,listDataConfig.iconProperty,params);
	}
	else{
		const dataItems = listDataConfig.listData;

		if(dataItems){
			 for(var i=0;i< dataItems.length;i++){
				 const item = {};
				 item['id'] = dataItems[i].data;
				 item['text'] = dataItems[i].label;
				 item.toString = function(){
					 return dataItems[i].label;
				 }
				 if(isEmpty(dataItems[i].icon) == false ){
					 item['icon'] = dataItems[i].icon;
				 }
				 map[dataItems[i].data] = item;
			 }
		 }
		return map;
	}
}

/**
 * 取得动态列表数据
 * @param {*} dataUrl 
 * @param {*} idProp 
 * @param {*} labProp 
 * @param {*} iconProperty 
 * @param {*} param
 */
export function loadListData(dataUrl, idProp, labProp, iconProperty, param) {

	if (param === undefined) {
		param = {};
	}

	if (isPlainObject(param)) {
		param = param.replace(/'/g, "\"");
		param = JSON.parse(param);
	}

	return ajax(dataUrl, param).then((data) => {
		const items = [];

		if (data) {

			for (let i = 0; i < data.length; i++) {
				const item = {};
				item['id'] = data[i][idProp];
				item['text'] = data[i][labProp];
				if (isEmpty(iconProperty) === false) {
					if (typeof (iconProperty) === 'function') {
						item['icon'] = iconProperty(data[i]);
					} else {
						item['icon'] = data[i][iconProperty];
					}
				}
				items.push(item);
			}
		}
		return items;

	}).catch(err => {
		console.error(err);
		return [];
	});

}

/**
 * 构建树形数据
 */
export function buildTreeNodes(url,params,callback) {

	let expandNodeLevel = -1;
    // 搜索值保留
    let search
    if(params.search){
        search = params.search
    }
	if(params && params.expandLevel !== undefined){
		expandNodeLevel = params.expandLevel;
	}
	let treeNodes = [];

	var requestId = "buildTree_" + new Date().getTime();
	
	if(url.indexOf("?") === -1){
		url = url + "?requestId=" + requestId
	}
	else{
		url = url + "&requestId=" + requestId
	}

	const data = fetchData(url,params);

	if(data){
		for(let i=0;i< data.length;i++){
			const node = {};
			
			node.id = data[i].id;
			node.text = data[i].text;
			node.icon__ = data[i].icon;
			node.icon = data[i].icon;
			node.group = data[i].group;
			node.level = data[i].level;
			node.actionGroupId = data[i].actionGroupId;
			node.expanded = data[i].state.expanded;
			node.selected = data[i].state.selected;
			node.nodeConfigId = data[i].nodeConfigId;
			node.nodeData = data[i].nodeData;
			node.state = data[i].state;
			node.isLeaf = data[i].isLeaf;
			//console.log(expandNodeLevel,data[i].level);
			if(data[i].isLeaf === false && (expandNodeLevel === -1 || data[i].state.expanded === true || data[i].level <= expandNodeLevel)){
			//if(data[i].isLeaf == false && ( expandNodeLevel == -1 || expandNodeLevel > data[i].level)){
                // = fetchData(url,{n_level : data[i].level, nodeid : data[i].id, nodeConfigId : data[i].nodeConfigId,expandLevel : expandNodeLevel});
				node.nodes = buildTreeNodes(url,{n_level : data[i].level, nodeid : data[i].id, nodeConfigId : data[i].nodeConfigId,expandLevel : expandNodeLevel,search:search});
			}
			else if(data[i].isLeaf === false){
				node.plus = true;
			}
			
			if(data[i].showTag && data[i].tags){
				node.count = data[i].tags[0];
			}
			
			treeNodes.push(node);
		}
		
		finishTreeBuild(url);

		if (typeof callback === "function"){
			callback(treeNodes);
        }
        
		return treeNodes;
	}
	else{
		return [];
	}
}

function finishTreeBuild(url){

	ajax(url,{finished : true});
}

/**
 * 取得动态树形列表数据
 */
export function loadTreeListData(dataUrl, param) {
	console.log("loadTreeListData:",param);

	return ajax(dataUrl, param).then((data) => {
		return data;
	}).catch(err => {
		console.log(err);
		return [];
	});
}

notification.config({
	placement: 'topRight',
	top: 50,
	duration:2.5,
});

export const openNotification = (type, title, message) => {
	notification[type]({
		message: title,
		description: message,
	});
};

export const openSuccessNotification = (message) => {
	notification['success']({
		message: '完成信息',
		description: message,
	});
};

export const openInfoNotification = (message) => {
	notification['info']({
		message: '提示信息',
		description: message,
	});
};

export const openWarningNotification = (message) => {
	notification['warning']({
		message: '警告信息',
		description: message,
	});
};

export const openErrorNotification = (message) => {
	notification['error']({
		message: '错误信息',
		description: message,
	});
};
